package edu.umassd.hciproject;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.ProgressDialog;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;

class AddressSearchTask extends AsyncTask<String,Void,List<Address>> {
	ProgressDialog dialog;
	IOException exception = null;
	private Geocoder geocoder;
	private Context myContext;
	private OnSearchFinishedListener myListener = null;
	
	public AddressSearchTask(Context context) {
		myContext = context;
		geocoder = new Geocoder(myContext,Locale.getDefault());
	}

	@Override
	protected List<Address> doInBackground(String... params) {
		// TODO Auto-generated method stub
		List<Address> locationResults = null;
		try {
			locationResults = geocoder.getFromLocationName(params[0], 10);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			exception = e;
		}
		return locationResults;
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		dialog = new ProgressDialog(myContext);
		dialog.setMessage("Searching...");
		dialog.setIndeterminate(true);
		dialog.setCancelable(false);
		dialog.show();
	}

	@Override
	protected void onPostExecute(List<Address> results) {
		dialog.dismiss();
		if (myListener != null) {
			myListener.onSearchFinished(results, exception);
		}
	}

	@Override
	protected void onCancelled() {
		// TODO Auto-generated method stub
		dialog.cancel();
	}
	
	public void setOnSearchFinishedListener(OnSearchFinishedListener listener) {
		myListener = listener;
	}

	public interface OnSearchFinishedListener {
		public void onSearchFinished(List<Address> results, IOException e);
	}
}

